package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"time"
	"zg6/o2-o-takeaway-backend-system/api/internal/request"
	"zg6/o2-o-takeaway-backend-system/common/global"
	"zg6/o2-o-takeaway-backend-system/common/models"
)

type Data struct {
	Cmd       uint   `json:"cmd"`        // 1:单发 2：群发
	ReceiveId uint   `json:"receive_id"` //接收者id
	Content   string `json:"content"`    //内容
	Types     uint   `json:"types"`      //通知类型
	Client    uint   `json:"client"`     //通知的群体
}
type Node struct {
	Conn *websocket.Conn
	Data Data
}

var OnlineUser = map[int]interface{}{}

func Ws(c *gin.Context) {
	userId := c.GetUint("userId")
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	OnlineUser[int(userId)] = Node{
		Conn: conn,
	}
	log.Println(OnlineUser)
}

func SendNotice(c *gin.Context) {
	var req request.SendNoticeReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}

	notice := models.Notices{
		Title:      req.Title,
		Content:    req.Content,
		ReceiveId:  req.ReceiveId,
		NoticeType: uint8(req.Types),
		Client:     uint8(req.Client),
	}
	if err := global.DB.Create(&notice).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}

	key := fmt.Sprintf("notice:%d:receive:%d", notice.Id, req.ReceiveId)
	marshal, err := json.Marshal(&notice)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"Data": nil,
		})
		return
	}
	global.RDB.Set(c, key, marshal, time.Minute*24)

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"Data": nil,
	})
}
